package com.im.file.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.im.file.bean.ImageData;
import com.im.file.service.ImageService;
import com.only.common.result.ResultMessage;

/**
 * 管理员处理Controller
 * 
 * @author 夏辉
 * @date 2014年6月4日 下午11:09:17
 * @version 0.0.1
 */
@Controller
@RequestMapping("/image")
public class ImageController {

	@Autowired
	ImageService imageService;

	@ResponseBody
	@RequestMapping("/upload.do")
	public Object userUpload(HttpServletRequest request, HttpServletResponse response) {
		ResultMessage rm = new ResultMessage();
		String userId = request.getParameter("userId");
		List<String> list = imageService.userUpload(request, userId);
		rm.put("ids", list);
		return rm;
	}

	@RequestMapping("/download.do")
	public void userDownload(String id, HttpServletRequest request, HttpServletResponse response) {

		if (StringUtils.isNotBlank(id)) {
			ImageData fileData = imageService.getImageData(id);
			if (null != fileData) {

				String fileName = fileData.getFullName();
				String agent = request.getHeader("USER-AGENT");
				try {
					if (StringUtils.isNotBlank(agent)) {
						if ((agent.toLowerCase().indexOf("msie") > 0 || agent.toLowerCase().indexOf("rv:11") > 0)) {// IE下载乱码处理
							fileName = URLEncoder.encode(fileName, "UTF-8");
							fileName = fileName.replace("+", "%20");// 处理空格变“+”的问题
						} else if (agent.toLowerCase().indexOf("java") > 0) {// FF
						}
					} else {
						fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				// response.setContentType("application/octet-stream");
				response.setCharacterEncoding("UTF-8");
				response.setContentType("multipart/form-data");
				response.setHeader("Content-Disposition", "attachment;filename=" + fileName + "");

				InputStream in = null;
				OutputStream out = null;
				try {
					StringBuilder fileSaveFullPathName = new StringBuilder();
					fileSaveFullPathName.append(fileData.getRootPath());
					fileSaveFullPathName.append(fileData.getNodePath());
					fileSaveFullPathName.append(fileData.getSaveFullName());

					File file = new File(fileSaveFullPathName.toString());
					if (file.exists()) {
						response.setHeader("Content-Length", file.length() + "");
						in = new FileInputStream(file);
						out = response.getOutputStream();
						byte[] b = new byte[2048];
						int length;
						while ((length = in.read(b)) > 0) {
							out.write(b, 0, length);
						}
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {// 这里主要关闭。
					if (null != in) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (null != out) {
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				// 返回值要注意，要不然就出现下面这句错误！
				// java+getOutputStream() has already been called for this
				// response
			}
		}
	}
}
